package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	"strings"

	"github.com/spf13/cobra"
)

var (
	instruction string
	options     []string
	savePath    string
)

func init() {

	promptCmd.PersistentFlags().StringVarP(&instruction, "instruction", "i", "", "instruction for prompt")
	promptCmd.PersistentFlags().Int32VarP(&modelId, "model", "m", 0, "model for prompt")
	promptCmd.PersistentFlags().StringSliceVarP(&options, "option", "o", []string{}, "model option for prompt")
	promptCmd.PersistentFlags().StringVarP(&savePath, "save", "s", "", "save path for prompt")

	assistantCmd.AddCommand(promptCmd)
}

var promptCmd = &cobra.Command{
	Use:   "prompt",
	Short: "Run cmd to generate llm prompt",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewLLMServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)

		model := utils.BuildUrn(utils.ModelUrnPrefix, modelId)

		in := &v1pb.GeneratePromptRequest{Instruction: instruction, Model: model}
		if len(options) > 0 {
			optionMap := make(map[string]string)
			for _, option := range options {
				a := strings.Split(option, "=")
				optionMap[a[0]] = a[1]
			}
			in.Options = optionMap
		}
		rsp, err := qclient.GeneratePrompt(ctxWithToken, in)
		if err != nil {
			return err
		}
		fmt.Println(rsp.Prompt)
		if savePath != "" {
			fmt.Println("save prompt to:", savePath)
			err = utils.WriteFile(savePath, rsp.Prompt)
			if err != nil {
				return err
			}
		}
		return nil
	},
}
